def splash_text(text):
    try:
        import pyi_splash
        pyi_splash.update_text(text)
    except:
        pass

splash_text("加载程序")   

from rpa import RPA
from lib import log
import webview
import fire
import sys, os


class JsAPI(object):
    def __init__(self, rpa:RPA) -> None:
        super().__init__()
        self.rpa = rpa

    def set_window(self, window):
        self.window = window

    def list_flow(self):
        return self.rpa.list_flow()

    def submit_flow(self, flow_name, flow_args, execute_time=None):
        return self.rpa.submit_flow(flow_name, flow_args, execute_time)

    def choose_file(self, allow_multiple=False, file_type='Excel Files (*.xlsx)'):
        result = self.window.create_file_dialog(webview.OPEN_DIALOG, allow_multiple=allow_multiple, file_types=(file_type, 'All files (*.*)'))
        return result

    def choose_dir(self):
        result = self.window.create_file_dialog(dialog_type=webview.FOLDER_DIALOG, directory='')
        return result

    def list_user(self):
        return self.rpa.list_user()

    def get_password(self, uid):
        return self.rpa.get_password(uid)
        


def close_splash():
    try:
        import pyi_splash
        pyi_splash.close()
    except:
        pass

def run(debug=False):
    splash_text("加载脚本...")
    r = RPA()
    api = JsAPI(r)
    splash_text("准备界面......")
    if debug == True:
        window = webview.create_window('RPA机器人', "http://localhost:9527", js_api=api, width=1000, height=888, text_select=True)
    else:
        global html_url
        html_url = os.path.join(os.getcwd(), "static", "index.html")
        window = webview.create_window('RPA机器人', html_url, js_api=api, width=1000, height=888, text_select=True)
    api.set_window(window)
    log.add_pywebview_handler(window)
    webview.start(debug=True, func=close_splash)

if __name__ == '__main__':
    fire.Fire(run)